using AutoMapper;
using Finance.Api.Write.Applications.Commands.库存盘点;
using Finance.Domain.盘点;
using Finance.ErrorCode;
using Finance.Infrastructure;
using MediatR;

namespace Finance.Api.Write.Applications.CommandHands.库存盘点
{
    public class CheckUpdateCommandHandler : IRequestHandler<CheckUpdateCommand, ApiResult<int>>
    {
        private readonly SqlsugarDb<CheckModel> db;
        private readonly IMapper mapper;

        public CheckUpdateCommandHandler(SqlsugarDb<CheckModel> db, IMapper mapper)
        {
            this.db = db;
            this.mapper = mapper;
        }

        public async Task<ApiResult<int>> Handle(CheckUpdateCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<int>();

            try
            {
                var entity = await db.FirstQuery().FirstAsync(x => x.Id == request.id);
                if (entity == null)
                {
                    result.message = "查无数据";
                    result.Code = Enumcode.fail;
                    return result;
                }

                entity = mapper.Map(request, entity);
                entity.UpdateTime = DateTime.Now;
                entity.UpdateName = "管理员"; // 固定值
                entity.LoginId = 1; // 固定值

                var updateResult = await db.Updata(entity);
                if (updateResult > 0)
                {
                    result.message = "库存盘点修改成功";
                    result.data = 1;
                    result.Code = Enumcode.ok;
                }
                else
                {
                    result.message = "库存盘点修改失败";
                    result.data = 0;
                    result.Code = Enumcode.fail;
                }
            }
            catch (Exception ex)
            {
                result.message = ex.Message;
                result.Code = Enumcode.fail;
                result.data = 0;
            }

            return await Task.FromResult(result);
        }
    }
} 